package com.edu.cdp.service.impl;

import com.edu.cdp.DTO.DetailDTO;
import com.edu.cdp.DTO.OrderDetailsDTO;
import com.edu.cdp.domain.Goods;
import com.edu.cdp.domain.Orders;
import com.edu.cdp.mapper.GoodsMapper;
import com.edu.cdp.mapper.OrdersMapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.edu.cdp.domain.OrderDetails;
import com.edu.cdp.service.OrderDetailsService;
import com.edu.cdp.mapper.OrderDetailsMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
* @author Yang Can
* @description 针对表【order_details】的数据库操作Service实现
* @createDate 2024-06-05 08:56:42
*/
@Service
@Slf4j
public class OrderDetailsServiceImpl extends ServiceImpl<OrderDetailsMapper, OrderDetails>
    implements OrderDetailsService {

    @Autowired
    OrderDetailsMapper orderDetailsMapper;
    @Autowired
    GoodsMapper goodsMapper;
    @Autowired
    OrdersMapper ordersMapper;

    @Override
    public OrderDetails update(OrderDetailsDTO orderDetails) {
        if (orderDetails.getNumber() <= 0) {
            log.error("数量不能小于0");
            return null;
        }

        OrderDetails orderDetail = orderDetailsMapper.selectById(orderDetails.getId());

        QueryWrapper<Goods> query = new QueryWrapper<>();
        query.eq("goods_name", orderDetails.getName());

        Goods good = goodsMapper.selectOne(query);

        if (orderDetails.getNumber() > good.getStock()) {
            log.error("库存不足");
            return null;
        }

        orderDetail.setNumber(orderDetails.getNumber());
        orderDetailsMapper.updateById(orderDetail);

        return orderDetail;
    }

    @Override
    public OrderDetails add(DetailDTO detailDTO) {
        Orders orders = ordersMapper.selectById(detailDTO.getOrderId());
        if (orders == null) {
            log.error("该订单不存在");
            return null;
        }

        Goods goods = goodsMapper.selectById(detailDTO.getGoodId());
        if (goods == null) {
            log.error("该商品不存在");
            return null;
        }
        OrderDetails orderDetails = new OrderDetails();
        BeanUtils.copyProperties(detailDTO, orderDetails);

        int insert = orderDetailsMapper.insert(orderDetails);
        if (insert > 0) {
            return orderDetails;
        } else {
            log.error("详情添加失败");

            return null;
        }
    }
}





